<?php
/**
 * Created by PhpStorm.
 * User: hansliao
 * Date: 2018/2/7
 * Time: 11:29
 */
namespace Admin\Controller;
//风控助理GID：4  状态权限2,3,31,32
//面审GID：4  状态权限4,41,42
//参意人GID：4  状态权限5
//终审GID：4  状态权限6
class OrderController extends AdminController{


    protected $uid;
    protected $gtos = array();
    protected $gid;
    protected function _initialize(){
        parent::_initialize();
        $this->uid = $_SESSION['onethink_admin']['user_auth']['uid'];
        $this->gtos[4] = '2';
        $this->gtos[5] = '4,41,42';
        $this->gtos[6] = '5';
        $this->gtos[7] = '6';
        $this->assign('title','进件列表');
        $this->gid = M('auth_group_access')->where("uid = $this->uid")->getField('group_id');
        if($this->uid != 1){
            $log = array();
            $log['uid'] = $this->uid;
            $log['oid'] = I('get.oid') ? I('get.oid') : I('post.oid');
            $log['action'] = CONTROLLER_NAME.'/'.ACTION_NAME;
            $log['get_data'] = json_encode(I('get.'));
            $log['post_data'] = json_encode(I('post.'));
            //$log['time'] = time();
            $log['ip'] = $_SERVER['REMOTE_ADDR'];
            M('logs')->add($log);
        }

        //print_r($log);
    }
    /**
     * 进件列表
     */
    public function index(){
        if($this->uid == 1){
            $where = array();
            $status = I('get.status');
            switch ($status){
                case 1:
                    $where['status'] = array('in','1');break;
                case 2:
                    $where['status'] = array('in','2,3,31,32,4,41,42');break;
                case 3:
                    $where['status'] = array('in','8');break;
                case 4:
                    $where['status'] = array('in','127,0');break;
                default:
                    break;
            }
            if(I('get.cid')){
                $cid = I('get.cid');
                $where['cid'] = array('LIKE',"%$cid%");
            }
            $where['mid'] = array('gt',0);
            $count = M('order')->where($where)->count();
            $Page       = new \Think\Page($count,25);
            $show       = $Page->show();
            $rs  = M('order')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('update_time desc')->select();
            foreach($rs as $k=>$v){
                $rs[$k]['mname'] = M('wechat_users')->where("id = {$v['mid']}")->getField("cname");
            }
            $this->assign('data',$rs);
            $this->assign('_page',$show);
            $this->assign('count',$count);
            $this->display('admin_index');
        }else{
            $where = array();
            $status = $this->gtos[$this->gid];
            $where['status'] = array('IN',$status);
            if($this->gid == 4){
                $doings = M('order_relations')->where("uid = $this->uid and status = 0")->getField('oid',true);
                if($doings){
                    $where['id'] = array('in',$doings);
                    $where['status'] = array('in','3,31,32,51');
                }
            }
            $rs  = M('order')->where($where)->order('update_time desc')->select();
            foreach($rs as $k=>$v){
                $rs[$k]['mname'] = M('wechat_users')->where("id = {$v['mid']}")->getField("cname");
            }
            $this->assign('data',$rs);
            $this->display();
        }

    }
    public function contract_list(){
        $where = array();
        $where['status'] = 51;
        $rs  = M('order')->where($where)->order('update_time desc')->select();
        foreach($rs as $k=>$v){
            $rs[$k]['mname'] = M('wechat_users')->where("id = {$v['mid']}")->getField("cname");
        }
        $this->assign('data',$rs);
        $this->display('index');
    }
    /**
     * 我来处理
     */
    public function lemedo(){
        $oid = I('get.oid');
        $info = M('order')->where("id = $oid")->find();
        if($info['status'] != 2){
            $this->error('不能操作该进件单！');exit;
        }
        $data = array();
        $data['oid'] = $oid;
        $data['uid'] = $this->uid;
        $data['create_time'] = time();
        if(M('order_relations')->add($data)){
            M('order')->where("id = $oid")->setField('status',3);
            $this->success('操作成功！',U('Order/index'));
        }else{
            $this->error('操作失败',U('Order/index'));
        }
    }

//    public function doing($oid){
//        $info = M('order')->where("id = $oid")->find();
//
//        $gid = M('auth_group_access')->where("uid = $this->uid")->getField('group_id');
//        $status = $this->gtos[$gid];
//        if($status != $info['status']){
//            $this->error('越权操作！');exit;
//        }
//        $data = array();
//        $data['status'] = $info['status'] +1;
//        $data['update_time'] = time();
//        //$status = $info['status'] +1
//        M('order')->where("id = $oid")->save($data);
//    }
    /**
     * 助理-》面审
     */
    public function send_to_ms(){
        $oid = I('post.oid');
        $allow_status = array(3,31,32);

        $status = M('order')->where("id = $oid")->getField('status');
        if(!in_array($status,$allow_status)){
            $this->error('越权操作！');exit;
        }
        $base = I('post.base');

        $base['status'] = 4;
        $base['update_time'] = time();

        $amount = I('post.amount');
        $contcts = I('post.contcts');
        $note = htmlspecialchars(I('post.note'));
        M()->startTrans();
        M('order')->where("id = $oid")->save($base);
        M('order_amount_info')->where("oid = $oid")->save($amount);
        foreach($contcts as $v){
            M('order_contacts')->where("oid = $oid and num = {$v['num']}")->save($v);
        }
        $note_data = array();
        $note_data['oid'] = $oid;
        $note_data['note_first'] = $note;
        $note_data['time_first'] = time();
        if(M('order_note')->where("oid = $oid")->count()>0){
            M('order_note')->where("oid = $oid")->save($note_data);
        }else{
            M('order_note')->add($note_data);
        }

        M('order_relations')->where("oid = $oid and uid = $this->uid")->setField('status',1);
        M()->commit();
        $this->success('提交成功！',U('Order/index'));
    }
    /**
     * 面审
     */
    public function send_to_yc(){
        $data = array();
        $oid = I('post.oid');
        $note = htmlspecialchars(I('post.note'));
        if(I('post.sub1')){//参意人
            $status = 5;
        }
        if(I('post.sub2')){//终审
            $status = 6;
        }
        if(I('post.sub3')){//助理预审通过
            $status = 31;
            if(!I('post.last_amount') || !I('post.last_duration')){
                $this->error('预审通过请填写预审金额&预审期限！');
            }
            $data['last_amount'] = I('post.last_amount');
            $data['last_duration'] = I('post.last_duration');
        }
        if(I('post.sub4')){//助理预审失败
            $status = 32;
            if(!I('post.fail_reason')){
                $this->error('预审失败请填写失败理由！');
            }
            $data['fail_reason'] = htmlspecialchars(I('post.fail_reason'));
        }
        //echo $status;exit;
        M()->startTrans();
        if($status == 31 || $status == 32){
            M('order_relations')->where("oid = $oid")->setField('status',0);
        }

        $data['update_time'] = time();
        $data['status'] = $status;
        $t1 = M('order')->where("id = $oid")->save($data);
        if($t1){
            M()->commit();
            M('order_note')->where("oid = $oid")->setField('note_second',$note);
            M('order_note')->where("oid = $oid")->setField('time_second',time());
            $this->success('提交成功！',U('Order/index'));
        }else{
            M()->rollback();
            $this->error('系统错误，请重试！');
        }
    }
    /**
     * 参意人&终审-》面审
     */
    public function back_to_ms(){
        $oid = I('post.oid');
        $note = htmlspecialchars(I('post.note'));
        if($this->gid = 6){
            $status = 41;
        }else{
            $status = 42;
        }
        M()->startTrans();
        $data = array();
        $data['update_time'] = time();
        $data['status'] = $status;
        $t1 = M('order')->where("id = $oid")->save($data);
        //$t1 = M('order')->where("id = $oid")->setField('update_time',time());
        if($t1){
            M()->commit();
            M('order_note')->where("oid = $oid")->setField('note_third',$note);
            M('order_note')->where("oid = $oid")->setField('time_third',time());
            $this->success('提交成功！',U('Order/index'));
        }else{
            M()->rollback();
            $this->error('系统错误，请重试！');
        }
    }
    public function detail($oid){
        $rs1 = M('order')->where("id = $oid")->find();
        $rs2 = M('order_amount_info')->where("oid = $oid")->find();
        $rs3 = M('order_contacts')->where("oid = $oid")->order("num asc")->select();
        $notes =M('order_note')->where("oid = $oid")->order('time_first desc')->find();
        $note_first = htmlspecialchars_decode($notes['note_first']);
        $note_second = htmlspecialchars_decode($notes['note_second']);
        $note_third = htmlspecialchars_decode($notes['note_third']);
        $pics = M('order_pics')->where("oid = $oid")->select();
        $this->assign('orderb',$rs1);
        $this->assign('ordera',$rs2);
        $this->assign('orderc',$rs3);
        $this->assign('note',$note_first);
        $this->assign('note_s',$note_second);
        $this->assign('note_t',$note_third);
        $this->assign('pics',$pics);
        if(in_array($rs1['status'],array('3','31','32')) && $this->gid = 4){
            $this->display();//助理
        }elseif(in_array($rs1['status'],array('51')) && $this->gid = 4){
            $this->display('contract_detail');//合同准备单
        }elseif(in_array($rs1['status'],array('4','41','42')) && $this->gid = 5){
            $this->display('middetail');//面审
        }elseif(in_array($rs1['status'],array('5','6')) && in_array($this->gid,array('6','7'))){
            $this->display('lastdetail');//参意人
        } else{
            $this->display('nodetail');//不能修改订单
        }
    }
    public function do_contract($oid){
        $oinfo = M('order')->where("id = $oid")->find();
        if($oinfo['status'] != 31){
            $this->error('操作失败，流程错误',U('Order/index'));
        }else{
            $data = array();
            $data['update_time'] = time();
            $data['status'] = 51;
            M('order')->where("id = $oid")->save($data);
            M('order_relations')->where("oid = $oid")->setField('status',1);

            $remark = "进件预审通过，预审金额{$oinfo['last_amount']}元，预审期限{$oinfo['last_duration']}月，请通知借款人尽快到公司签约！";
            $this->mass_send($oinfo['cname'],$oinfo['mobile_tel'],'预审通过',$remark,$oinfo['mid'],$oid);

            $this->success('操作成功',U('Order/index'));
        }
    }
    public function do_repeat($oid){
        $status = M('order')->where("id = $oid")->getField('status');
        if($status != 51){
            $this->error('操作失败，流程错误',U('Order/index'));
        }else{
            $data = array();
            $data['update_time'] = time();
            $data['status'] = 3;
            M('order')->where("id = $oid")->save($data);
            M('order_relations')->where("oid = $oid")->setField('status',0);
            $this->success('操作成功',U('Order/detail','oid='.$oid));
        }
    }
    public function do_success($oid){
        $status = M('order')->where("id = $oid")->getField('status');
        if($status != 51){
            $this->error('操作失败，流程错误',U('Order/index'));
        }else{
            $data = array();
            $data['update_time'] = time();
            $data['status'] = 8;
            M('order')->where("id = $oid")->save($data);
            M('order_relations')->where("oid = $oid")->setField('status',1);
            $this->success('操作成功',U('Order/index'));
        }
    }

    public function do_fail($oid){
        $oinfo = M('order')->where("id = $oid")->find();
        if($oinfo['status'] != 32){
            $this->error('操作失败，流程错误',U('Order/index'));
        }else{
            $data = array();
            $data['update_time'] = time();
            $data['status'] = 127;
            M('order')->where("id = $oid")->save($data);
            M('order_relations')->where("oid = $oid")->setField('status',1);

            $remark = "进件预审未通过：{$oinfo['fail_reason']}";
            $this->mass_send($oinfo['cname'],$oinfo['mobile_tel'],'预审失败',$remark,$oinfo['mid'],$oid);

            $this->success('操作成功',U('Order/index'));
        }
    }
    public function download_exl($oid){
        Vendor('excel.PHPExcel');
        $obj = new \PHPExcel();
        $rs1 = M('order')->where("id = $oid")->find();
        if(!$rs1){
            exit('别乱来！');
        }
        if(!in_array($rs1['status'],array(3,31,32))){
            exit('别乱来！');
        }
        $rs2 = M('order_amount_info')->where("oid = $oid")->find();
        $rs3 = M('order_contacts')->where("oid = $oid")->order("num asc")->select();
        $data = array();
        $data[] = date('Y-m-d',$rs1['create_time']);
        $data[] = $rs1['cname'];
        $data[] = $rs1['cid'];
        $data[] = $rs1['mobile_tel'];
        $data[] = $rs1['home_tel'];
        $data[] = $rs1['company_tel'];
        $data[] = $rs1['bank_card_id'];
        $data[] = $rs1['cr_addr'];
        $data[] = $rs1['home_addr'];

        $data[] = $rs1['company_name'];
        $data[] = $rs1['company_addr'];
        $data[] = $rs1['company_type'];
        $data[] = $rs1['ctype'];

        $data[] = $rs2['province'];
        $data[] = $rs2['city'];
        $data[] = $rs2['channel'];
        $data[] = $rs2['purpose'];

        $data[] = $rs1['worktime'];
        $data[] = $rs1['aincome'];
        $data[] = $rs1['hp'];
        $data[] = $rs1['ht'];

        $data[] = $rs2['amount'];
        $data[] = $rs2['duration'];
        $data[] = '月';

        $data[] = $rs1['edu'];
        $data[] = $rs1['mar'];
        $data[] = $rs1['qq'];
        $data[] = $rs1['email'];
        $data[] = $rs1['postal_addr'];
        $data[] = $rs1['position'];
        $data[] = $rs1['profession'];
        $data[] = $rs1['industry'];

        $data[] = $rs1['if_one'];
        $data[] = '';
        $data[] = $rs1['if_two'];
        $data[] = '';
        $data[] = $rs1['if_three'];

        $s = 1;
        foreach($rs3 as $v){
            if($s > 3){
                break;
            }
            $data[] = $v['srelations'];
            $data[] = $v['name'];
            $data[] = $v['cid'];
            $data[] = $v['tel'];
            $data[] = $v['home_addr'];
            $data[] = $v['work_addr'];
            $data[] = $v['company_addr'];
            $s++;
        }

        $title = array();
        $title[] = '贷款日期';
        $title[] = '姓名';
        $title[] = '身份证号';
        $title[] = '手机号码';
        $title[] = '家庭座机';
        $title[] = '单位座机';
        $title[] = '银行卡号';
        $title[] = '户籍地址';
        $title[] = '家庭地址';
        $title[] = '工作单位';
        $title[] = '单位地址';
        $title[] = '公司性质';
        $title[] = '申请人员类别';
        $title[] = '进件省份';
        $title[] = '进件城市';
        $title[] = '进件渠道';
        $title[] = '借款用途';
        $title[] = '工作时间';
        $title[] = '年收入';
        $title[] = '房产情况';
        $title[] = '房产类型';
        $title[] = '贷款金额';
        $title[] = '贷款期限';
        $title[] = '贷款期限单位(月,天)';
        $title[] = '学历';
        $title[] = '婚姻';
        $title[] = 'QQ号码';
        $title[] = '邮箱地址';
        $title[] = '通讯地址';
        $title[] = '职位';
        $title[] = '职业';
        $title[] = '公司行业';
        $title[] = '三个月内是否跨平台申请借款';
        $title[] = '三个月内跨平台申请借款平台个数';
        $title[] = '三个月内是否跨平台借款负债';
        $title[] = '三个月内跨平台借款负债平台个数';
        $title[] = '身份证与姓名是否核实';

        $title[] = '第一联系人社会关系';
        $title[] = '第一联系人姓名';
        $title[] = '第一联系人身份证';
        $title[] = '第一联系人手机号';
        $title[] = '第一联系人家庭地址';
        $title[] = '第一联系人工作单位';
        $title[] = '第一联系人单位地址';

        $title[] = '第二联系人社会关系';
        $title[] = '第二联系人姓名';
        $title[] = '第二联系人身份证';
        $title[] = '第二联系人手机号';
        $title[] = '第二联系人家庭地址';
        $title[] = '第二联系人工作单位';
        $title[] = '第二联系人单位地址';

        $title[] = '第三联系人社会关系';
        $title[] = '第三联系人姓名';
        $title[] = '第三联系人身份证';
        $title[] = '第三联系人手机号';
        $title[] = '第三联系人家庭地址';
        $title[] = '第三联系人工作单位';
        $title[] = '第三联系人单位地址';

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF');

        $obj->getActiveSheet(0)->setTitle('sheet1');   //设置sheet名称
        $_row = 1;

        $i = 0;
        foreach($title AS $v){   //设置列标题
            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
            $i++;
        }
        $_row++;

        $i = 0;
        foreach($data AS $_v){
            $obj->getActiveSheet(0)->setCellValue($cellName[0+$i] . ($_row), ' '.$_v);
            $i++;
        }
        $fileName = uniqid();


        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="links_out'.$fileName.'.xlsx"');
        header('Cache-Control: max-age=0');
        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
        $objWrite->save('php://output');exit;
    }

    protected function mass_send($cname,$mobile_tel,$status,$remark,$mid,$oid){
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx979bd6584f24e813&secret=9941111af041057505a3f6360b7cd739";
//        $rs = https_request($url);
        $a = M('wechat_config')->where("key = 'access_token'")->find();
        if(time() - $a['create_time'] > 6000){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx979bd6584f24e813&secret=9941111af041057505a3f6360b7cd739";
            $rs = https_request($url);
            $access_token  = json_decode($rs,true)['access_token'];
            M('wechat_config')->where("`key` = 'access_token'")->save(array('value'=>$access_token,'create_time'=>time()));
        }else{
            $access_token = $a['value'];
        }
        //$access_token= "8_OIwlW0goY4EEUMuOrncwjtAFlTejSLbDITS25s4vtwtnjzixIclH--L8moB7tJBZkDpdibHlNfJ3Yq5vyNustDoZu7qminV5ER33v63xg1Pcu3BNq4VHi9ytCsIggW99rRUHubRMHZtC3idZTVKaAJAACR";
        $openid = M('wechat_users')->where("id = $mid")->getField('openid');

        $url  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
        $data = array();
        $data['touser'] = $openid;
        $data['template_id'] = 'uhqyjV2OKfYdf1grwvhyIWJ4ToY2Zql8HjNpbwS7qH0';
        $data['url'] = 'http://www.jinqinuo.com/detail/'.$oid;
        $data['topcolor'] = '#FF0000';
        $data['data'] = array();
        $data['data']['first'] = array('color'=>'#000000','value'=>'进件状态变更！');
        $data['data']['keyword1'] = array('color'=>'#173177','value'=>$cname);
        $data['data']['keyword2'] = array('color'=>'#173177','value'=>'(电话)'.$mobile_tel);
        $data['data']['keyword3'] = array('color'=>'#8E8E8E','value'=>$status);
        $data['data']['remark'] = array('color'=>'#FF0000','value'=>$remark);

        $rs = https_request($url,json_encode($data));
        //print_r($rs);
        //print_r($rs);
    }
}